package com.zy.ems.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zy.ems.common.base.BaseController;
import com.zy.ems.common.exception.ApiException;
import com.zy.ems.common.exception.BaseErrorStatus;
import com.zy.ems.common.exception.BusinessException;
import com.zy.ems.common.page.PaginationResult;
import com.zy.ems.common.util.GetParameterUtil;
import com.zy.ems.common.util.JsonUtils;
import com.zy.ems.common.util.ResultTool;
import com.zy.ems.common.util.StringUtils;
import com.zy.ems.model.MemberEntity;
import com.zy.ems.service.MemberService;
import com.zy.ems.utils.exceptions.MemberCode;
import com.zy.ems.utils.exceptions.UserCode;

@RestController
@RequestMapping("/member")
public class MemberController extends BaseController {

    @Autowired
    private MemberService memberService;

    @RequestMapping(value = "login.json", method = RequestMethod.POST)
    public Object login(HttpServletRequest request) {
        String userName = StringUtils
                .parseStr(request.getParameter("userName"));
        String password = StringUtils
                .parseStr(request.getParameter("password"));

        if (StringUtils.isEmpty(userName, password)) {
            return ResultTool.error(BaseErrorStatus.sys_008);
        }

        try {
            MemberEntity memberEntity = memberService.login(userName, password);

            if (memberEntity == null) {
                return ResultTool.error(MemberCode.mem_1001);
            }

            return ResultTool.success(memberEntity);
        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(e);
        }
    }

    @RequestMapping(value = "register.json", method = RequestMethod.POST)
    public Object register(HttpServletRequest request) {

        try {
            GetParameterUtil util = new GetParameterUtil();
            StringBuilder para = new StringBuilder();
            para.append("userName").append(",password").append(",mobile")
                    .append(",email");

            Map<String, String> param = util.getPara(request, para.toString());
            if (StringUtils.isEmpty(param.get("userName"),
                    param.get("password"))) {
                return ResultTool.error(MemberCode.mem_1002);
            }

            if (StringUtils.isEmpty(param.get("mobile"), param.get("email"))) {
                return ResultTool.error(MemberCode.mem_1003);
            }

            boolean result = true ;//this.memberService.register(param);

            if (result) {
                return ResultTool.success();
            }
            else {
                return ResultTool.error(MemberCode.sys_007.addMsg("注册失败."));
            }

        }
        catch (BusinessException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(e);
        }
    }

    @RequestMapping(value = "/getMemberList.json", method = RequestMethod.GET)
    public Object getMemberList(HttpServletRequest request) {
        String q = request.getParameter("q");
        String start = request.getParameter("start");
        String size = request.getParameter("size");

        if (StringUtils.isEmpty(q, start, size)) {
            return ResultTool.error(BaseErrorStatus.sys_008);
        }

        // 检测登录状态
        boolean checkToken = checkToken(request);
        if (!checkToken) {
            return ResultTool.error(UserCode.B_USER_2005);
        }

        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            if (StringUtils.isNotBlank(q)) {
                paramMap = JsonUtils.readJson2Map(q, Object.class);
            }

            paramMap.put("size", size);
            paramMap.put("start", start);

            PaginationResult<MemberEntity> data = this.memberService
                    .getMemberList(paramMap);

            return ResultTool.success(data);
        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(BaseErrorStatus.ERROR);
        }
    }

    @RequestMapping(value = "/deleteMember.json", method = RequestMethod.POST)
    public Object deleteMember(HttpServletRequest request) {
        String memberId = StringUtils.parseStr(request.getParameter("id"));

        if (StringUtils.isEmpty(memberId)) {
            return ResultTool.error(BaseErrorStatus.sys_008);
        }

        boolean accessToken = this.checkToken(request);

        if (!accessToken) {
            return ResultTool.error(UserCode.B_USER_2005);
        }

        try {
            this.memberService.deleteMemberById(StringUtils.parseInt(memberId));

            return ResultTool.success();
        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(BaseErrorStatus.sys_008);
        }
    }

    /**
     * 检测用户名是否存在
     * 
     * @param request
     * @return
     */
    public Object checkUserNameExist(HttpServletRequest request) {
        String userName = StringUtils
                .parseStr(request.getParameter("userName"));

        if (StringUtils.isEmpty(userName)) {
            return ResultTool.error(BaseErrorStatus.sys_008);
        }

        try {
            MemberEntity memberEntity = this.memberService
                    .getByUserName(userName);

            if (memberEntity == null) {
                return ResultTool.success();
            }

            return ResultTool.error(UserCode.B_USER_2007);
        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(BaseErrorStatus.ERROR);
        }

    }

    /**
     * 增加学生
     */
    @RequestMapping(value = "/addMember.json", method = RequestMethod.POST)
    public Object addMember(HttpServletRequest request) {
        String memberJsons = StringUtils
                .parseStr(request.getParameter("member"));

        if (StringUtils.isEmpty(memberJsons)) {
            return ResultTool.error(BaseErrorStatus.sys_008);
        }

        MemberEntity memberEntity = JsonUtils.readJson2Entity(memberJsons,
                MemberEntity.class);

        if (memberEntity == null) {
            logger.error("增加学生解析JSON 失败");
            return ResultTool.error(BaseErrorStatus.sys_008);
        }

        try {
            if (StringUtils.isEmpty(memberEntity.getUserName(),
                    memberEntity.getPassword())) {
                return ResultTool.error(BaseErrorStatus.sys_008);
            }

            MemberEntity tmpEntity = this.memberService
                    .getByUserName(memberEntity.getUserName());

            if (tmpEntity != null) {
                return ResultTool.error(UserCode.B_USER_2007);
            }

            this.memberService.addMember(memberEntity);

            return ResultTool.success();
        }
        catch (ApiException e) {
            return ResultTool.error(e);
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResultTool.error(BaseErrorStatus.ERROR);
        }
    }
}
